package com.google.code.v8config;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;

/**
 *
 * @author yvad
 */
public final class FileUtils {
    
    //--------------------------------------------------------------------------
    public static final Charset CHARSET = Charset.forName("UTF-8");
    public static final String FILE_SEPARATOR
            = System.getProperty("file.separator");
    public static final int DATA_PREFIX = 0xfeff;    
    
    //--------------------------------------------------------------------------
    public static void removeDirComponents(File dir)
            throws IOException {
        
        for(File file : dir.listFiles()) {
            if(file.isDirectory())
                removeDirComponents(file);
            if(!file.delete())
                throw new IOException("Can not delete file <"+file.getPath()+">");
        }
        
    }
    public static byte[] readFileAsBytes(File file) 
            throws IOException {
            
        byte[] buffer = new byte[(int)file.length()];

        FileInputStream fis = null;
        try {

            fis = new FileInputStream(file);
            if(fis.read(buffer)!=buffer.length)
                throw new IOException("Only part was read");

        } finally {
            if(fis!=null)
                fis.close();
        }

        return buffer;
    }
    public static String readFileAsString(File file) 
            throws IOException {
        return new String(readFileAsBytes(file), CHARSET);
    }
    public static DataList readFileAsDataList(File file) 
            throws IOException {
        
        String data = readFileAsString(file);
        DataList datalist = new DataList();
        datalist.unpack(data);
        
        return datalist;
    }
    public static void writeFile(File file, byte[] buffer) 
            throws IOException {
        
        FileOutputStream fos = null;
        try {

            fos = new FileOutputStream(file);
            fos.write(buffer);
            fos.flush();

        } finally {
            if(fos!=null)
                fos.close();
        }
        
    }
    public static void writeFile(File file, String string) 
            throws IOException {
        writeFile(file, string.getBytes(CHARSET));
    }
    public static void writeFile(File file, DataList datalist) 
            throws IOException {
        writeFile(file, datalist.pack());
    }
            
    //--------------------------------------------------------------------------
}
